package com.m4f.gaeweb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.google.appengine.api.NamespaceManager;

public class EnviromentFilter implements Filter {
	private static final String ENV_DEVEL = "-devel-";
	private static final String ENV_TEST = "-test-";
	private static final String ENV_PROD = "-prod-";
	
	//private static final String ENV_PARAM_NAME = "_env";
	
	private String enviroment;
	

	@Override
	public void destroy() {
				
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		/*if(request.getParameter(ENV_PARAM_NAME) != null) {
			this.setEnviroment(request.getParameter(ENV_PARAM_NAME));
		}*/
		
	    String currentNamespace = NamespaceManager.get();
	    try {
	    	NamespaceManager.set(this.enviroment);
	    } catch(Exception e) {
	    	NamespaceManager.set(currentNamespace);
	    }
		chain.doFilter(request, response);		
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String env = config.getInitParameter("enviroment");
		this.setEnviroment(env);
	}
	
	private void setEnviroment(String env) {
		if(ENV_DEVEL.equals(env)) {
			this.enviroment = ENV_DEVEL;
		} else if(ENV_TEST.equals(env)) {
			this.enviroment = ENV_TEST;
		} else if(ENV_PROD.equals(env)){
			this.enviroment = ENV_PROD;
		} else { 
			this.enviroment = ""; // INFO No namespace selected!.
		}
	}

}
